import React, {useEffect, useRef, useState} from "react";
import type {SelectProps} from "antd";
import {Select, Tooltip} from "antd";
import {getSelectOptionsApi} from "@/api/system";

export interface IRemoteSelectProps extends SelectProps {
    action: string;
    httpData: any;
    method: 'get' | 'post' | 'put' | "del" | 'upload';
}

interface IOptionProps {
    label: string
    value: any;
    disabled: boolean
    className?: string;
    title?: string;

    [name: string]: any;

    children?: Omit<IOptionProps, 'children'>[];
}

const SlRemoteSelect: React.FC<IRemoteSelectProps> = (props) => {
    const {action, httpData, method = 'get', ...customProps} = props
    const {value, options} = customProps
    const [loading, setLoading] = useState<boolean>(false);
    const [realOptions, setRealOptions] = useState<IOptionProps[]>([])
    const optionRef = useRef<IOptionProps[]>([]);
    const getSelectOptions = () => {
        const params: any = {
            url: action,
            data: httpData ? httpData : {},
            method
        }
        getSelectOptionsApi(params).then((res: any) => {
            optionRef.current = res;
            setRealOptions(res);
        }).finally(() => {
            setLoading(false);
        })
    }
    const onFocus = () => {
        setLoading(true);
        if (!action) {
            optionRef.current = options as any || [];
            setRealOptions(options as any || []);
            setLoading(false);
        }
        getSelectOptions();
    }
    useEffect(() => {
        if (value) {
            getSelectOptions();
        }
    }, [value]);
    return (
        <Select
            {...customProps}
            loading={loading}
            options={realOptions}
            maxTagPlaceholder={(omittedValues) => (
                <Tooltip
                    styles={{root: {pointerEvents: 'none'}}}
                    title={omittedValues.map(({label}: any) => label).join(', ')}
                >
                    <span>更多</span>
                </Tooltip>
            )}
            onFocus={onFocus}>
        </Select>
    )
}

export default SlRemoteSelect;